<%--
  Created by IntelliJ IDEA.
  User: W
  Date: 2022/1/2
  Time: 11:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
%>
<html>
    <head>
        <title>Test</title>
        <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
        <script>
            let http_url = "<%=basePath%>/server/${sessionID}";
            let socket_url = http_url.replace('http', 'ws');
            let socket;
            let commandID = 0;
            function openSocket() {
                socket = new WebSocket(socket_url);
                socket.onopen = function () {};
                socket.onmessage = function (msg) {
                    var data = JSON.parse(msg.data);
                    if (data['type'] === 'reply') {
                        switch (data['name']) {
                            case 'connect':
                                connect();
                                break;
                            case 'match':
                                match(data);
                                break;

                        }
                    }
                }
            }

            function connect() {
                console.log('成功连接到服务器!');
            }

            function match(data) {
                console.log("匹配成功--", data['partnerID']);
            }

            function matchPartner() {
                if (socket === undefined) {
                    console.log("socket未定义");
                    return false;
                }
                var data = {
                    commandID: ++ commandID,
                    name: 'match',
                    sessionID: '${sessionID}'
                };
                socket.send(JSON.stringify(data));
            }

        </script>
    </head>
    <body>
        <button onclick="openSocket();">开启socket</button>
        <button onclick="matchPartner();">匹配对手</button>
    </body>
</html>
